import React, {Component, Fragment} from 'react';
import {Button, Divider, Select, DatePicker, Form,} from 'antd';
import moment from 'moment';
import $ from 'jquery';
import CKssylqfxhzb from './ChaKanBody/CKssylqfxhzb';
import CKkzsysjl from './ChaKanBody/CKkzsysjl';
import CKslyclhxfxbgd from './ChaKanBody/CKslyclhxfxbgd'
import CKzksscxtjl from './ChaKanBody/CKzksscxtjl'
import CKzksscxtjlx2 from './ChaKanBody/CKzksscxtjlx2'
import './ChaKan.css';

const Option = Select.Option;
const biaoge_list = ['入窑生料原材料化学分析报告单',
    '出磨生料原材料化学分析报告单',
    '控制室原始记录',
    '生熟原料全分析汇总表',
    '中控室烧成系统运行记录', '中控室烧成系统运行记录续表',];

class ChaKan extends Component {
    constructor(props) {
        super(props);
        this.state = {
            selectValue: '0',//表格选项
            riqi: null,//查表日期
            timeChose: 0,//班次
            upperData: [{'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},],
            bottomData: [[[], [], [], [], [],], [[], [], [], [], [],], [[], [], [], [], [],],],//页面下半部分的数据
            person: '',//传入的值班人员
            zhibiao: [null, null, null, null, null, null, null, null, null],//从数据库获取的标准
            biaoge_display: ['none', 'none', 'none', 'none', 'none', 'none',],//控制表格的显示，默认全不显示
            leixing_dispaly: false,//控制表格下拉框中 中控室表格是否显示
            print_dis: 'none',//控制打印按钮是否显示,默认不显示
        }
    }

    //判定是否已登录，是否有权限
    componentWillMount() {
        if (window.localStorage.privilege < 1) {
            this.props.history.push('/');
        } else {
            if (window.localStorage.department > 1) {//部门是化验室之外的可以看中控表
                this.setState({
                    riqi: moment().format("YYYY-MM-DD"),
                    leixing_dispaly: true,
                })
            }
        }
        fetch('/api/JudgePrivilege', {
            method: 'post',
            credentials: 'include',
            headers: {
                'Content-Type': 'application/json',
                'authorization': window.localStorage.authorization,
            }
        })
            .then(res => res.json())
            .then(data => {
                if (data['code'] === 0) {
                }
                else {
                    this.props.history.push('/index');
                }
            })
            .catch(error => console.error('Error:', error))
    }


    //选择表格类型
    handleChange = (value) => {
        this.setState({
            selectValue: value,
            upperData: [{'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},],
            bottomData: [[[], [], [], [], [],], [[], [], [], [], [],], [[], [], [], [], [],],],
            zhibiao: [null, null, null, null, null, null, null, null, null],
        });
        this.setVisibility(value);
    };
    //选择时间范围
    handleChangeTime = (e) => {
        if (!e) {
            return;
        }
        this.setState({
            riqi: e.format("YYYY-MM-DD"),
            upperData: [{'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},],
            bottomData: [[[], [], [], [], [],], [[], [], [], [], [],], [[], [], [], [], [],],],
            zhibiao: [null, null, null, null, null, null, null, null, null],
        })
    };
    //修改班次
    handleTimeChange = (e) => {
        const x = parseInt(e);
        this.setState({
            timeChose: x,
        });
    };
    //控制表格显示
    setVisibility = (table) => {
        let display = ['none', 'none', 'none', 'none', 'none', 'none',]
        display[table] = '';
        this.setState({
            biaoge_display: display
        })
    };
    //提交按钮事件
    handleQuery = (e) => {
        const tableChose = this.state.selectValue
        const leixing_list = ['RYS', 'CMS', 'KZS', 'SSY', 'ZKS', 'ZKSX2'];
        const riqi = this.state.riqi;
        const jsondata = {
            'startRiqi': riqi,
            'startXiaoshi': 0,
            'endRiqi': riqi,
            "endXiaoshi": 23,
            'leixing': leixing_list[tableChose],
            'zhonglei': 0,
        };
        let tableQueryURL = '';
        if (tableChose < 4) {
            tableQueryURL = '/api/HuaYS/query';
        } else {
            tableQueryURL = '/api/ZhongKS/query';
        }
        fetch(tableQueryURL, {
            method: 'POST',
            credentials: "include",
            body: JSON.stringify(jsondata), // data can be `string` or {object}!
            headers: {
                'Content-Type': 'application/json',
                'authorization': window.localStorage.authorization,
            }
        })
            .then(res => res.json())
            .then(data => {
                console.log("data:" +data["code"]);
                if (data['code'] === 0) {//判定是否成功
                    let upperData = [{'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                        {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                        {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                        {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                        {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},
                        {'shuju': []}, {'shuju': []}, {'shuju': []}, {'shuju': []},];
                    let buttomData = [[[], [], [], [], [],], [[], [], [], [], [],], [[], [], [], [], [],],];
                    for (let i = 0; i < data['data'].length; i++) {
                        if (data['data'][i]['zhonglei'] === 1) {//类型为1是上表数据
                            let shuju = data['data'][i]['shuju'];//取出data中的数据
                            let str = shuju.split(',');//去除数据中的string逗号
                            let a = [];//临时的number数据数组
                            for (let i = 0; i < str.length; i++)//将string转换成number
                                a[i] = parseFloat(str[i]);
                            data['data'][i]['shuju'] = a;//数据数组归还给data
                            const xiaoshi = data['data'][i]['xiaoshi'];//按小时排序把数据传给upperdata
                            upperData[xiaoshi] = data['data'][i];
                        }
                        else if (data['data'][i]['zhonglei'] === 2) {//类型为2是下表数据
                            const xiaoshi = data['data'][i]['xiaoshi'];//按小时排序把数据传给upperdata
                            buttomData[xiaoshi] = eval(data['data'][i]['shuju']);
                        }
                    }
                    this.setState({//传值给upperData和bottomData
                        upperData: upperData,
                        bottomData: buttomData,
                        print_dis: 'block',//打印按钮出现
                    });
                }
            })
            .catch(error => console.error('Error:', error))
            .then(response => console.log('Success:', response));

        /**从服务器获取指标**/
        const zhibiaoleixing_list = ['RYS', 'CMS', 'KZS', 'SSY', 'ZKS', 'ZKS']
        const leixing = {'leixing': zhibiaoleixing_list[tableChose]};
        fetch("/api/zhibiao/query", {
            method: 'POST',
            body: JSON.stringify(leixing), // data can be `string` or {object}!
            headers: {
                'Content-Type': 'application/json',
                'authorization': window.localStorage.authorization,
            }
        })
            .then(res => res.json())
            .then(data => {
                    if (data['code'] === 0 && data['zhibiao']['leixing'] === leixing_list[tableChose]) { //判定是否成功
                        let zhi = data['zhibiao']['zhibiao'];
                        const zhibiao = zhi.split(',');//去除指标的逗号
                        let a = [];
                        for (let i = 0; i < zhibiao.length; i++)
                            a[i] = parseFloat(zhibiao[i]);
                        this.setState({
                            zhibiao: a,
                        });
                    }
                }
            )
            .catch(error => console.error('Error:', error))
            .then(response => console.log('Success:', response));
        this.setVisibility(tableChose);//改变表格显示状态
    };

    handlePrint = () => {
        window.document.body.innerHTML = window.document.getElementById("abc").innerHTML;
        // window.document.body.innerHTML = "<CKslyclhxfxbgd />";
        window.print();
        window.location.reload();
    };

    render() {
        return (
            <div className='chakan' style={{padding: '1%'}}>
                <div className='chakan_head' style={{margin: 5}}>
                    <Divider/>
                    <span>请选择表格类型：</span>
                    <Select defaultValue="0" style={{width: 230, margin: '10px'}} onChange={this.handleChange}>
                        <Option value="0">入窑生料原材料化学分析报告单</Option>
                        <Option value="1">出磨生料原材料化学分析报告单</Option>
                        <Option value="2">控制室原始记录</Option>
                        <Option value="3">生熟原料全分析汇总表</Option>
                        <Option value="4" disabled={!this.state.leixing_dispaly}>中控室烧成系统运行记录</Option>
                        <Option value="5" disabled={!this.state.leixing_dispaly}>中控室烧成系统运行记录续表</Option>
                    </Select>

                    <span>请选择日期：</span>
                    <DatePicker
                        // showTime
                        defaultValue={moment(this.state.riqi)}
                        format="YYYY-MM-DD"
                        placeholder='选择日期'
                        onChange={this.handleChangeTime}
                        // onOk={this.handleChangeTime}
                        style={{margin: '10px'}}
                    />
                    选择班次：<Select defaultValue='0' onChange={this.handleTimeChange} style={{margin: '10px'}}>
                    <Option value="0">0点班</Option>
                    <Option value="1">8点班</Option>
                    <Option value="2">16点班</Option>
                </Select>
                    <Button type="primary" style={{margin: '10px'}} onClick={this.handleQuery}>查询</Button>
                    <Divider/>
                </div>
                <div className='chakan_body' id="abc">
                    <CKslyclhxfxbgd style={{display: this.state.biaoge_display[0]}} riqi={this.state.riqi}
                                    timeChose={this.state.timeChose} standard={this.state.zhibiao}
                                    upperData={this.state.upperData} person={this.state.person} title={biaoge_list[0]}/>
                    <CKslyclhxfxbgd style={{display: this.state.biaoge_display[1]}} riqi={this.state.riqi}
                                    timeChose={this.state.timeChose} standard={this.state.zhibiao}
                                    upperData={this.state.upperData} person={this.state.person} title={biaoge_list[1]}/>
                    <CKkzsysjl style={{display: this.state.biaoge_display[2]}} riqi={this.state.riqi}
                               bottomData={this.state.bottomData}
                               timeChose={this.state.timeChose} zhibiao={this.state.zhibiao}
                               upperData={this.state.upperData} person={this.state.person} title={biaoge_list[2]}/>
                    <CKssylqfxhzb style={{display: this.state.biaoge_display[3]}} riqi={this.state.riqi}
                                  timeChose={this.state.timeChose}
                                  person={this.state.person} standard={this.state.zhibiao}
                                  upperData={this.state.upperData} title={biaoge_list[3]}/>
                    <CKzksscxtjl style={{display: this.state.biaoge_display[4]}} riqi={this.state.riqi}
                                 timeChose={this.state.timeChose}
                                 person={this.state.person} standard={this.state.zhibiao}
                                 FormData={this.state.upperData} title={biaoge_list[4]}/>
                    <CKzksscxtjlx2 style={{display: this.state.biaoge_display[5]}} riqi={this.state.riqi}
                                   timeChose={this.state.timeChose} person={this.state.person}
                                   standard={this.state.zhibiao} upperData={this.state.upperData}
                                   bottomData={this.state.bottomData} title={biaoge_list[5]}/>

                </div>
                <Button type="primary"
                        style={{marginRight: '10px', float: 'right', margin: '10px', display: this.state.print_dis}}
                        onClick={this.handlePrint}>打印</Button>
            </div>

        )

    }
}

export default ChaKan;